<template>
  <div class="app-container">
    <h4 class="form-header h4">当前品牌信息</h4>
    <el-form ref="titleForm" :model="titleForm" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="品牌编号" prop="brandId">
            <el-input v-model="titleForm.brandId" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="品牌名称" prop="categoryId">
            <el-input v-model="titleForm.brandName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">关联分类信息</h4>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:brandcategory:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete(row)"
          v-hasPermi="['product:brand:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="brandcategoryList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌id" align="center" prop="brandId" />
      <el-table-column label="分类id" align="center" prop="categoryId" />
      <el-table-column label="品牌名称" align="center" prop="brandName" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:brandcategory:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:brandcategory:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加分类关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-cascader
          style="width: 460px"
          v-model="orderCategory"
          :options="categoryOptions"
          :props="categoryProps"
          expand-trigger="hover"
        ></el-cascader>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-form label-width="100px">
      <el-form-item
        style="text-align: center; margin-left: -120px; margin-top: 30px"
      >
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {listCategory, listCategoryTree} from "@/api/product/category";
import {addBrandcategory, delBrandcategory, listBrandcategory, updateBrandcategory,} from "@/api/product/brandcategory";
import {getBrand} from "@/api/product/brand";

export default {
  name: "Brandcategory",
  data() {
    return {
      categoryProps: {
        value: "catId",
        label: "name",
        children: "children",
      },
      categoryOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品牌分类关联表格数据
      brandcategoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandId: null,
        categoryId: null,
      },
      // 标题表单参数
      titleForm: {
        brandId: null,
        brandName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 分类递进关联列表
      orderCategory: [],
      // 旧分类id
      oldCategoryId: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询品牌分类关联列表 */
    getList() {
      // 品牌id
      const brandId = this.$route.params.brandId;
      // 加入条件
      this.queryParams.brandId = brandId;
      this.loading = true;
      listBrandcategory(this.queryParams)
        .then((response) => {
          if (response && response.rows && response.rows.length > 0) {
            this.titleForm = response.rows[0];
          } else {
            getBrand(brandId).then((response) => {
              this.titleForm.brandId = response.data.brandId;
              this.titleForm.brandName = response.data.name;
            });
          }
          this.brandcategoryList = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        })
        .catch((error) => {
          this.$modal.msgError(error.message);
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        brandId: null,
        categoryId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.categoryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.orderCategory = [];
      this.open = true;
      this.title = "添加品牌分类关联";

      // 加载分类列表
      listCategory().then((response) => {
        this.categoryOptions = this.handleTree(
          response.rows,
          "catId",
          "parentCid"
        );
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      this.oldCategoryId = row.categoryId;

      //加载分类列表
      listCategory().then((response) => {
        this.categoryOptions = this.handleTree(
          response.rows,
          "catId",
          "parentCid"
        );
      });

      // 分类id递归查询
      listCategoryTree(row.categoryId).then((response) => {
        this.orderCategory = response.data;
      });

      this.open = true;
      this.title = "修改品牌分类关联";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title == "添加品牌分类关联") {
            this.form.brandId =
              this.$route.params && this.$route.params.brandId;
            this.form.categoryId = this.orderCategory[2];
            // delete this.form.categoryId;
            addBrandcategory(this.form)
              .then((response) => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("新增成功");
                }
              })
              .catch((error) => {
                this.$modal.msgError(response.msg);
              })
              .finally(() => {
                this.open = false;
                this.getList();
              });
          } else {
            this.form.brandId =
              this.$route.params && this.$route.params.brandId;
            this.form.categoryId = this.orderCategory[2];
            updateBrandcategory(this.form, this.oldCategoryId)
              .then((response) => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("修改成功");
                }
              })
              .catch((error) => {
                this.$modal.msgError(response.msg);
              })
              .finally(() => {
                this.open = false;
                this.getList();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // ids数组里面新增row.categoryId
      this.ids.push(row.categoryId);
      this.$modal
        .confirm('是否确认删除品牌分类编号为"' + this.ids + '"的数据项？')
        .then((response) => {
          this.$modal.msgSuccess("删除成功");
          return delBrandcategory(this.ids, this.titleForm.brandId);
        })
        .catch((error) => {
          this.$modal.msgError(response.msg);
        })
        .finally(() => {
          // 清空ids数组
          this.ids = [];
          this.getList();
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/brandcategory/export",
        {
          ...this.queryParams,
        },
        `brandcategory_${new Date().getTime()}.xlsx`
      );
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: "/product/brand" };
      this.$tab.closeOpenPage(obj);
    },
  },
};
</script>
